package jvm.deadlock;

import java.util.concurrent.TimeUnit;

/**
 * @author LoneRanger
 */
public class DeadLockTest {

	public static void main(String[] args) {
		Object resourceA = new Object();
		Object resourceB = new Object();

		new Thread(new MyTask(resourceA, resourceB), "Thread A").start();
		new Thread(new MyTask(resourceB, resourceA), "Thread B").start();
	}

}

class MyTask implements Runnable {

	Object resource1, resource2;

	public MyTask(Object resource1, Object resource2) {
		this.resource1 = resource1;
		this.resource2 = resource2;
	}

	@Override
	public void run() {
		synchronized (resource1) {
			System.out.println(String.format("%s 自己持有%s，尝试持有%s",//
					Thread.currentThread().getName(), resource1, resource2));

			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			synchronized (resource2) {
				System.out.println(String.format("%s 同时持有%s，%s",//
						Thread.currentThread().getName(), resource1, resource2));
			}
		}
	}
}
